OLD_URL = "http://downloads.sourceforge.net/project/libjpeg/libjpeg/%(VERSION)s/jpegsrc.v%(VERSION)s.tar.gz"
IJGJPEG_LINUX_URL = "http://www.ijg.org/files/jpegsrc.v%(VERSION)s.tar.gz"
IJGJPEG_WINDOWS_URL = "http://www.ijg.org/files/jpegsr%(VERSION)s.zip"

def urldecider( machine, dirs, version):
  if version == "6b":
    return OLD_URL % {"VERSION" : version}
  else:
    return { "Linux" : IJGJPEG_LINUX_URL % {"VERSION" : version} , 
             "Windows" : IJGJPEG_WINDOWS_URL % {"VERSION" : version} }[machine.platform]

URL = urldecider

VERSIONS = ["6b", "8c"]
DEFAULT_VERSION = "8c"

import os, shutil
from source.builders import NMakeBuilder, ConfigureMakeBuilder

class JPegBuilder( NMakeBuilder ):
  """ subclass of ConfigureMakeBuilder with custom configure step """

  def configure(self):
    os.chdir( self.extractedpath )    
    shutil.copy("jconfig.vc", "jconfig.h")
    if self.version in ["6b"]:
      shutil.copy("makelib.ds", "jpeg.mak")
      shutil.copy("makeapps.ds", "apps.mak")

  def make(self):
    os.chdir( self.extractedpath )
    self.execute( "nmake debug=1 /f Makefile.vc libjpeg.lib" )
    shutil.move("libjpeg.lib", "libjpegD.lib")
    self.deletepattern(".", ".*\\.obj")
    self.execute( "nmake nodebug=1 /f Makefile.vc libjpeg.lib" )

  def install(self):
    self.copyfile( "libjpeg.lib", self.getlibdir())
    self.copyfile( "libjpegD.lib", self.getlibdir())
    self.copyfile( "jconfig.h", self.getincludedir())
    self.copyfile( "jerror.h", self.getincludedir())
    self.copyfile( "jmorecfg.h", self.getincludedir())
    self.copyfile( "jpeglib.h", self.getincludedir())


class JPegLinux( ConfigureMakeBuilder ):

  def configureparameters(self):
    return ["--enable-shared"]

class JPegOldLinux( ConfigureMakeBuilder ):
# old jpeg version fails to build with ./libtool not found, solved by using "LIBTOOL=libtool"
  def make(self):
    os.chdir( self.extractedpath )
    if self.machine.cores > 1:
      self.execute( "make LIBTOOL=libtool -j " + str(self.machine.cores) )
    else:
      self.execute( "make LIBTOOL=libtool" )

# old jpeg version needed directories to be available"
  def install(self):
    if not os.path.exists( self.installpath() + "/bin" ):
      os.makedirs( self.installpath() + "/bin" )
      os.makedirs( self.installpath() + "/lib" )
      os.makedirs( self.installpath() + "/include" )
      os.makedirs( self.installpath() + "/man/man1" )

    ConfigureMakeBuilder.install(self)

#todo use old version builder for building older version

def decider( machine, dirs ):
  return { "Linux" : JPegLinux, "Windows" : JPegBuilder }[machine.platform]

BUILDER = decider

